package com.venusj.springcloud.service;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.concurrent.TimeUnit;

/**
 * Created By Administrator
 * User: VenusZ
 * Date: on 2020/3/23 22:42
 * Desc:
 */
@Service
public class PaymentService {

    public String paymentInfo_OK (Integer id) {
        return "线程池：" + Thread.currentThread().getName() + " paymentInfo_OK, id:" + id;
    }

    /**
     * 当前方法允许3秒内完成，如果超时会触发fallback方法
     * @param id
     * @return
     */
    @HystrixCommand(fallbackMethod = "paymentInfo_ERROR_FALLBACK", commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")
    })
    public String paymentInfo_ERROR (Integer id) {

        //  程序超时异常 会触发服务降级
        Integer time = 5;
        try {
            TimeUnit.SECONDS.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 程序运行抛出异常时，也会触发服务降级
//        int i = 5/0;


        return "线程池：" + Thread.currentThread().getName() + " paymentInfo_ERROR, id:" + id + " 耗时(:s)" +  time;
    }

    public String paymentInfo_ERROR_FALLBACK (Integer id) {
        return "线程池：" + Thread.currentThread().getName() + " 系统繁忙,请稍后再试 id:" + id + " 服务降级";
    }

    // 服务熔断
    @HystrixCommand(fallbackMethod = "paymentCicuitBreakerFallBack", commandProperties = {
            @HystrixProperty(name="circuitBreaker.enabled", value = "true"), // 是否开启断路器
            @HystrixProperty(name="circuitBreaker.requestVolumeThreshold", value = "10"), // 请求次数
            @HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds", value = "10000"), // 时间窗口期
            @HystrixProperty(name="circuitBreaker.errorThresholdPercentage", value = "60") // 失败率达到多少后跳闸
    })
    public String paymentCicuitBreaker(@PathVariable("id") Integer id)
    {
        if (id < 0)
        {
            throw new RuntimeException("**************id 不能负数");
        }
        String serialId = IdUtil.simpleUUID();
        return Thread.currentThread().getName() + "\t" + "调用成功流水号：" + serialId;
    }

    public String paymentCicuitBreakerFallBack(@PathVariable("id") Integer id)
    {
        return "ID 不能为负数，请稍后再试!!! id:" + id;
    }
}
